<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="150px"
    >
      <el-form-item label="缩略图" prop="bannerUrl">
        <img :src="dataForm.bannerUrl" v-if="dataForm.id" style="width: 40px;height: 40px;">
        <img :src="dataForm.bannerUrl" v-if="!dataForm.id" style="width: 40px;height: 40px;">
        <el-upload
          class="upload-demo"
          :action="url"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :on-success="handleAvatarSuccess"
          list-type="picture"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传png文件且大小不超过250KB</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="url地址" prop="bannerLink">
        <el-input v-model="dataForm.bannerLink" placeholder="url地址"></el-input>
      </el-form-item>
      <el-form-item label="排序编号" prop="bannerSort">
        <el-input v-model="dataForm.bannerSort" placeholder="排序编号"></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="isAlive">
        <el-radio v-model="dataForm.isAlive" label="1">启用</el-radio>
        <el-radio v-model="dataForm.isAlive" label="0">禁用</el-radio>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      visible: false,
      dataForm: {
        id: 0,
        bannerUrl: "",
        bannerLink: "",
        bannerSort: "",
        isAlive: "1"
      },
      dataRule: {
        bannerUrl: [
          { required: true, message: "缩略图不能为空", trigger: "blur" }
        ],
        bannerLink: [
          { required: true, message: "URL地址不能为空", trigger: "blur" }
        ],
        bannerSort: [
          { required: true, message: "排序不能为空", trigger: "blur" }
        ],
        isAlive: [
          { required: true, message: "是否启用不能为空", trigger: "blur" }
        ]
      },
      url: ""
    };
  },
  mounted() {
    this.url = this.$http.adornUrl(
      `/operate/bannerinfo/upload?token=${this.$cookie.get("token")}`
    );
  },
  methods: {
    init(id) {
      this.dataForm.id = id || 0;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(
              `/operate/bannerinfo/info/${this.dataForm.id}`
            ),
            method: "get",
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataForm.bannerUrl = data.bannerInfo.bannerUrl
              this.dataForm.bannerLink = data.bannerInfo.bannerLink
              this.dataForm.bannerSort = data.bannerInfo.bannerSort
              this.dataForm.isAlive = data.bannerInfo.isAlive + ''
            }
          })
        }
      })
    },
    handleAvatarSuccess(response, file, fileList) {
      this.fileList = fileList
      this.successNum++
      if (response && response.code === 0) {
        if (this.num === this.successNum) {
          this.$confirm('操作成功, 是否继续操作?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).catch(() => {
            this.visible = false
          })
        }
        this.dataForm.bannerUrl = response.url
      } else {
        this.$message.error(response.msg)
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/png'
      if (!isJPG) {
        this.$message.error('上传封面只能是 png 格式!')
      }
      const isSize = new Promise(function(resolve, reject) {
        let width = 1029
        let height = 390
        let _URL = window.URL || window.webkitURL
        let img = new Image()
        img.onload = function() {
          let valid = img.width == width && img.height == height
          valid ? resolve() : reject()
        }
        img.src = _URL.createObjectURL(file)
      }).then(
        () => {
          return file
        },
        () => {
          this.$message.error('上传的banner缩略图必须是1029*390!')
          return Promise.reject()
        }
      )
      return isJPG  && isSize
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `/operate/bannerinfo/${!this.dataForm.id ? "save" : "update"}`
            ),
            method: "post",
            data: this.$http.adornData({
              id: this.dataForm.id || undefined,
              bannerUrl: this.dataForm.bannerUrl,
              bannerLink: this.dataForm.bannerLink,
              bannerSort: parseInt(this.dataForm.bannerSort),
              isAlive: parseInt(this.dataForm.isAlive)
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    }
  }
};
</script>
